﻿using BaoVeThanhDia.Buttons;
using BaoVeThanhDia.FileSetting;
using BaoVeThanhDia.GamePlay;
using BaoVeThanhDia.GamePlay.Eff;
using BaoVeThanhDia.GamePlay.Monsters;
using BaoVeThanhDia.GamePlay.Towers;
using BaoVeThanhDia.MapAndUpgrade;
using BaoVeThanhDia.MapFolder;
using BaoVeThanhDia.Sound;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Info;
using Microsoft.Phone.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Navigation;
namespace BaoVeThanhDia
{
    public partial class GamePage : PhoneApplicationPage
    {
        public static ContentManager contentManager;
        public static List<Tower> towers;
        public static List<Monster> monsters;
        public static float Scale;
        public static float Speed;// 1x và 2x
        public static Vector2 Dolech;
        public static Map map;
        public static int Money;
        public static int Level;
        public static int CurLife, Life;
        public static int Mana;

        string GameStatus;

        GameTimer timer;
        static SpriteBatch spriteBatch;
        Random rand;

        private BackgroundWorker bw = new BackgroundWorker();

        int waveMonster;
        int countToCreateAMonster;
        bool isComPleteCreateWave;
        int maxMonsterinWave;
        public static long Score;
        long curHighScore;
        int Star, oldStar;

        List<Button> Gamebuttons, EndGameButtons;
        List<Button> BookItems;
        List<MapEffect> mapEffects;

        Texture2D Otrong;
        Vector2 start, curtouch;
        SpriteFont font, priceFont, waveFont;
        UpgradeTower upgradeTower;

        bool isSelectTower; // đang giữ 1 tháp để đặt vào ô trống
        int TypeTowerSelected;// loại tháp đang chọn để đặt vào ô trống
        Tower tower;// tháp phụ lưu trữ thông tin tháp sẽ được đặt vào ô trống
        bool isBookOpenned;// đang mở sách skill hay ko
        bool isSelectSkill;
        int indexSkill;
        int countAddLoc;
        Vector2 indexAddLoc;
        bool isBoQua;
        float[] countTimeToUseEffectAgain = new float[4];
        int[] TimeToUseEffectAgain = new int[4];
        Texture2D TopicImage, ImageStar;
        CustomSoundEffect dat_thap, click;
        int loainhac;
        BangGia banggia;
        public static int countMagicTower;

        public GamePage()
        {
            InitializeComponent();
            // Get the content manager from the application
            contentManager = (Application.Current as App).Content;
            // Create a timer for this page
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(200000);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;

            banggia = new BangGia();
            rand = new Random();
            loainhac = rand.Next(10000) % 4;
            Level = MapAndUpgrade.MapAndUpgrade.LevelSelected;
            #region OGG
            bw.WorkerReportsProgress = true;
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            bw.RunWorkerAsync();
            #endregion

            #region nơi khởi tạo các giá trị
            click = new CustomSoundEffect("sounds/effect/Click_Button");
            dat_thap = new CustomSoundEffect("sounds/effect/Items/Dat_Tru");
            Gamebuttons = new List<Button>();
            #region set các nút bấm
            Gamebuttons.Add(new Button("", "images/gamebutton/gold_bar", new Vector2(3, 3), Vector2.Zero, new Vector2(167, 48), 1f));
            Gamebuttons.Add(new Button("", "images/gamebutton/wave_bar", new Vector2(350, 30), Vector2.Zero, new Vector2(135, 46), 1f));
            Gamebuttons.Add(new Button("", "images/gamebutton/heartbar1", new Vector2(640, 7), Vector2.Zero, new Vector2(129, 32), 1f));
            Gamebuttons.Add(new Button("", "images/gamebutton/heart", new Vector2(740, -3), Vector2.Zero, new Vector2(55, 50), 1f));
            Gamebuttons.Add(new Button("", "images/gamebutton/clock_bar", new Vector2(640, 60), Vector2.Zero, new Vector2(132, 32), 1f));
            Gamebuttons.Add(new Button("", "images/gamebutton/clock", new Vector2(740, 50), Vector2.Zero, new Vector2(56, 52), 1f));
            for (int i = 0; i < 5; i++)
                Gamebuttons.Add(new Button(i.ToString(), "images/gamebutton/thap" + i.ToString(), new Vector2(280 + 70 * i, 410), Vector2.Zero, new Vector2(64, 64), 1f));
            Gamebuttons.Add(new Button("book", "images/gamebutton/skillbook0", new Vector2(650, 410), Vector2.Zero, new Vector2(64, 64), 1f));
            Gamebuttons.Add(new Button("buyMana", "images/gamebutton/crystal", new Vector2(720, 410), Vector2.Zero, new Vector2(64, 64), 1f));
            Gamebuttons.Add(new Button("pause", "images/gamebutton/itempau", new Vector2(20, 410), Vector2.Zero, new Vector2(64, 65), 1f));
            Gamebuttons.Add(new Button("speed1", "images/gamebutton/itemfast", new Vector2(100, 410), Vector2.Zero, new Vector2(64, 65), 1f));
            Gamebuttons.Add(new Button("speed2", "images/gamebutton/itemfast1", new Vector2(100, 410), Vector2.Zero, new Vector2(64, 65), 1f));
            Gamebuttons.Add(new Button("PauseFrame", "images/gamebutton/board", new Vector2(250, 76), Vector2.Zero, new Vector2(200, 219), 1.5f));
            Gamebuttons.Add(new Button("PauseFrame_Play", "images/gamebutton/play", new Vector2(325, 200), Vector2.Zero, new Vector2(100, 107), 1.5f));
            Gamebuttons.Add(new Button("PauseFrame_RePlay", "images/gamebutton/replay", new Vector2(200, 190), Vector2.Zero, new Vector2(100, 100), 1f));
            Gamebuttons.Add(new Button("PauseFrame_Exit", "images/gamebutton/menu1", new Vector2(500, 190), Vector2.Zero, new Vector2(100, 100), 1.1f));
            Gamebuttons.Add(new Button("PauseFrame", "images/Introduction/ribbon", new Vector2(222, 100), Vector2.Zero, new Vector2(355, 90), 1f));


            #endregion
            EndGameButtons = new List<Button>();
            #region set các hình ảnh khi kết thúc game
            EndGameButtons.Add(new Button("", "images/winlose/footer", new Vector2(0, 206), Vector2.Zero, new Vector2(400, 137), 2f));

            EndGameButtons.Add(new Button("Lose", "images/winlose/text", new Vector2(200, 120), Vector2.Zero, new Vector2(200, 60), 2f));
            EndGameButtons.Add(new Button("Lose_RePlay", "images/winlose/choilai", new Vector2(225, 350), Vector2.Zero, new Vector2(150, 66), 1f));
            EndGameButtons.Add(new Button("Lose_Menu", "images/winlose/menu", new Vector2(425, 350), Vector2.Zero, new Vector2(150, 66), 1f));

            EndGameButtons.Add(new Button("Win", "images/winlose/text1", new Vector2(200, 120), Vector2.Zero, new Vector2(300, 64), 4 / 3f));
            EndGameButtons.Add(new Button("Win_Face", "images/winlose/face", new Vector2(225, 350), Vector2.Zero, new Vector2(150, 66), 1f));
            EndGameButtons.Add(new Button("Win_Next", "images/winlose/tieptuc", new Vector2(425, 350), Vector2.Zero, new Vector2(150, 66), 1f));
            #endregion
            BookItems = new List<Button>();
            #region set các item trong sách
            for (int i = 0; i < 4; i++)
                BookItems.Add(new Button(i.ToString(), "images/gamebutton/itemplus" + (i + 1).ToString(), new Vector2(730, 110 + i * 76), Vector2.Zero, new Vector2(64, 71), 1f));
            BookItems.Add(new Button("", "images/gamebutton/skillbook1", new Vector2(650, 410), Vector2.Zero, new Vector2(64, 64), 1f));
            #endregion

            #endregion
            isBoQua = false;
            NewGame();
        }
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            // Perform a time consuming operation and report progress.
            // System.Threading.Thread.Sleep(50);
            //   worker.ReportProgress()
            AudioManager.LoadSounds("song_game" + loainhac.ToString() + ".ogg");
        }
        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (MainPage.isNen) AudioManager.PlaySound("song_game" + loainhac.ToString() + ".ogg", true);
        }

        private void NewGame()
        {
            countMagicTower = 10;
            Star = 1;
            oldStar = FileThanh.Stars[Level];
            curHighScore = FileThanh.HighScore[Level];
            Score = 0;
            GameStatus = "Play";
            waveMonster = 0;
            countAddLoc = 0;
            Mana = 100 + Level;
            if (MapAndUpgrade.File_Upgrade_Star.ItemBought[7])
            {
                Mana += Mana / 2;
            }
            Life = 15 + Level / 10;
            CurLife = 15 + Level / 10;
            Speed = 1.0f;
            Dolech = new Vector2(0, 0);
            isBookOpenned = false;
            isSelectSkill = false;
            map = new Map(contentManager);
            map.Load(contentManager);
            Scale = 0.5f;
            towers = new List<Tower>();
            monsters = new List<Monster>();
            upgradeTower = new UpgradeTower();
            mapEffects = new List<MapEffect>();
            for (int i = 0; i < 4; i++)
            {
                countTimeToUseEffectAgain[i] = 100;
                TimeToUseEffectAgain[i] = 100;
            }
            countToCreateAMonster = 0;
            isComPleteCreateWave = false;
            maxMonsterinWave = waveMonster / 3 + 5;
            Money = 100 + Level * 30;
            if (MapAndUpgrade.File_Upgrade_Star.ItemBought[0])
            {
                Money += Money / 5;
            }
        }

        private bool NewWave()
        {
            float speed = rand.Next(5, 5 + waveMonster / 6);
            int typeMonster = 1;
            #region tính loại quái xuất hiện
            if (waveMonster <= 5)
            {
                #region 5 wave đầu toàn quái nhỏ, tại wave 5 cho thêm 1 quái to
                if (waveMonster == 5 && maxMonsterinWave == 1)
                {
                    typeMonster = rand.Next(10, 15);
                }
                else
                {
                    typeMonster = rand.Next(1, waveMonster + 1);
                }
                #endregion
            }
            else if (waveMonster <= 10)
            {
                #region 5 wave tiếp theo quái to lên dần, tại wave 10 cho 2 con trùm
                if (waveMonster == 10 && maxMonsterinWave == 2)
                {
                    typeMonster = 5;
                }
                else if (waveMonster == 10 && maxMonsterinWave == 1)
                {
                    typeMonster = rand.Next(10, 15);
                }
                else
                {
                    typeMonster = rand.Next(1, 9);
                }
                #endregion
            }
            else if (waveMonster <= 20)
            {
                #region từ wave 10 đến wave 20, quái khá mạnh
                if (waveMonster == 20 && maxMonsterinWave == 1)
                {
                    typeMonster = 15;
                }
                else
                {
                    typeMonster = rand.Next(6, 10);
                }
                #endregion
            }
            else
            {
                #region từ wave 10 đến wave 20, quái khá mạnh
                if (waveMonster == 30 && maxMonsterinWave < 3)
                {
                    typeMonster = 15;
                }
                else
                {
                    typeMonster = rand.Next(8, 14);
                }
                #endregion
            }
            #endregion
            int HP = rand.Next(25, 40) * (waveMonster + 1) + Level * (35 + waveMonster) + (waveMonster > 15 ? waveMonster * (Level + 3) : 0);
            monsters.Add(new Monster(typeMonster, map.getBegin(), speed, HP));
            maxMonsterinWave--;
            if (maxMonsterinWave <= 0)
            {
                Mana += 5;
                return true;
            }
            return false;
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            #region giải phóng bộ nhớ
            //MapAndUpgrade.MapAndUpgrade.contentManager.Unload();
            #endregion
            #region các biến hệ thống
            // Set the sharing mode of the graphics device to turn on XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);
            #endregion
            // TODO: use this.content to load your game content here
            #region load các tài nguyên
            dat_thap.Load(contentManager);
            font = contentManager.Load<SpriteFont>("fonts/XuFont");
            waveFont = contentManager.Load<SpriteFont>("fonts/WaveFont");
            priceFont = contentManager.Load<SpriteFont>("fonts/PriceFont");
            map.Load(contentManager);
            Otrong = contentManager.Load<Texture2D>("images/border");
            TopicImage = contentManager.Load<Texture2D>("images/maps/bg/" + Level / 10);
            foreach (Button button in Gamebuttons)
            {
                button.Load(contentManager);
            }
            foreach (Button button in EndGameButtons)
            {
                button.Load(contentManager);
            }
            foreach (Button button in BookItems)
            {
                button.Load(contentManager);
            }
            foreach (Tower tower in towers)
            {
                tower.Load(contentManager);
            }
            if (upgradeTower.getVisible())
            {
                upgradeTower.Load(contentManager);
            }
            click.Load(contentManager);
            #endregion

            if (MainPage.isNen) AudioManager.PlaySound("song_game" + loainhac.ToString() + ".ogg", true);
            // Start the timer
            timer.Start();

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // Stop the timer
            AudioManager.StopSound("song_game" + loainhac.ToString() + ".ogg");
            timer.Stop();
            if (GameStatus.Equals("Play"))
            {
                GameStatus = "Pause";
            }
            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);

            base.OnNavigatedFrom(e);
        }

        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            if (Speed == 1 && isBoQua)
            {
                isBoQua = false;
            }
            else
            {
                if (GameStatus.Equals("Play") || GameStatus.Equals("Pause"))
                {
                    if (!GameStatus.Equals("Pause"))
                    {
                        #region các sự việc tự diễn ra
                        #region nếu bị thua
                        if (CurLife <= 0)
                        {
                            CurLife = 0;
                            if (waveMonster > 15)
                            {
                                FileThanh.SaveFile(Level, waveMonster > 25 ? 1 : 0, (int)(Score > curHighScore ? Score : curHighScore));
                                File_Upgrade_Star.Star += waveMonster > 25 ? 1 : 0;
                                File_Upgrade_Star.SaveStar();
                            }
                            GameStatus = "Lose";
                        }
                        #endregion
                        #region nếu thắng
                        if (isComPleteCreateWave && monsters.Count == 0)// nếu đã sinh hết đợt mà đều bị xóa thì qua đợt mới
                        {
                            if (waveMonster >= 30)
                            {
                                if (CurLife == 15) Star = 3;
                                else if (CurLife > 8) Star = 2;
                                else Star = 1;
                                FileThanh.SaveFile(Level, Star > oldStar ? Star : oldStar, (int)(Score + CurLife * 200 + Money > curHighScore ? Score + CurLife * 200 + Money : curHighScore));
                                File_Upgrade_Star.Star += oldStar > Star ? 0 : Star - oldStar;
                                File_Upgrade_Star.SaveStar();
                                GameStatus = "Win";
                            }
                            else
                            {
                                monsters.Clear();
                                waveMonster++;
                                maxMonsterinWave = waveMonster / 5 + 5;
                                Debug.WriteLine("Level " + Level + " ở wave " + waveMonster + "có " + maxMonsterinWave + "quái");
                                isComPleteCreateWave = false;
                                countToCreateAMonster = 0;
                            }
                        }
                        #endregion
                        #region kiểm tra việc sinh quái
                        countToCreateAMonster++;
                        if (countToCreateAMonster > 30000) countToCreateAMonster = 0;
                        // TODO: Add your update logic here
                        if (countToCreateAMonster > 300 && countToCreateAMonster % 30 == 0)
                        {
                            if (!isComPleteCreateWave && NewWave())
                            {
                                countToCreateAMonster = 0;
                                isComPleteCreateWave = true;
                            }
                        }
                        #endregion
                        #region hồi lại các skill
                        for (int i = 0; i < 4; i++)
                        {
                            if (countTimeToUseEffectAgain[i] < 100) countTimeToUseEffectAgain[i] += 100f / TimeToUseEffectAgain[i];
                        }
                        #endregion
                        isBoQua = true;
                        #region thêm lốc vào mưa sao băng
                        if (countAddLoc > 0)
                        {
                            countAddLoc++;
                            if (countAddLoc % 10 == 0) mapEffects.Add(new MapEffect(0, indexAddLoc, countAddLoc / 10, false));
                            if (countAddLoc >= 40) countAddLoc = 0;
                        }
                        #endregion
                        #region trụ bắn
                        foreach (Tower tower in towers)
                        {
                            tower.GetBuff(towers);
                            tower.Ban();
                        }
                        #endregion
                        #region quái vật di chuyển
                        for (int i = 0; i < monsters.Count; i++)
                        {
                            monsters[i].Walk();
                        }
                        #endregion
                        #region kiểm tra các hiệu ứng
                        for (int i = 0; i < mapEffects.Count; i++)
                        {
                            if (!mapEffects[i].getVisible()) mapEffects.RemoveAt(i);
                            else mapEffects[i].isActiveEffect();
                        }
                        #endregion
                        #endregion
                    }
                    #region xử lí sự kiện của ng dùng
                    TouchCollection touchs = TouchPanel.GetState();
                    foreach (TouchLocation touch in touchs)
                    {
                        if (touch.State == TouchLocationState.Pressed)
                        {
                            start = touch.Position;
                            curtouch = touch.Position;
                        }
                        if (touch.State == TouchLocationState.Moved)
                        {
                            #region sự kiện vuốt
                            Dolech += touch.Position - curtouch;
                            curtouch = touch.Position;
                            if (Dolech.X > 0) Dolech.X = 0;
                            if (Dolech.Y > 0) Dolech.Y = 0;
                            if (-Dolech.X + 800 > Map.SizeOfMatrix.Y * 128 * Scale) Dolech.X = 800 - Map.SizeOfMatrix.Y * 128 * Scale;
                            if (-Dolech.Y + 480 > Map.SizeOfMatrix.X * 128 * Scale) Dolech.Y = 480 - Map.SizeOfMatrix.X * 128 * Scale;
                            if (upgradeTower.getVisible())
                            {
                                upgradeTower.isTouch(curtouch, contentManager);
                            }
                            else
                            {
                                if (!isSelectTower)
                                {
                                    foreach (Button button in Gamebuttons)
                                    {
                                        if (GameStatus.Equals("Pause"))
                                        {
                                            if (button.getName().StartsWith("PauseFrame") && (!button.getName().Equals("PauseFrame")) && button.isTouch(curtouch, Vector2.Zero))
                                            {
                                                button.isTouch(curtouch, Vector2.Zero);
                                            }
                                        }
                                        else if (!button.getName().Equals(""))
                                        {
                                            button.isTouch(curtouch, Vector2.Zero);
                                        }
                                    }
                                    if (isBookOpenned)
                                    {
                                        foreach (Button button in BookItems)
                                        {
                                            if (!button.getName().Equals(""))
                                            {
                                                button.isTouch(curtouch);
                                            }
                                        }
                                    }
                                }
                            }
                            #endregion
                        }
                        if (touch.State == TouchLocationState.Released)
                        {
                            curtouch = touch.Position;
                            if (Vector2.Distance(start, curtouch) <= 30) // tính là sự kiện bấm nút
                            {
                                if (GameStatus.Equals("Pause"))
                                {
                                    #region xử lí việc bấm trong giao diện pause
                                    foreach (Button button in Gamebuttons)
                                    {
                                        if (button.getName().StartsWith("PauseFrame") && (!button.getName().Equals("PauseFrame")) && button.isTouch(curtouch, Vector2.Zero))
                                        {
                                            click.Play();
                                            button.setTouch(false);
                                            if (button.getName().Equals("PauseFrame_Play"))
                                            {
                                                GameStatus = "Play";
                                                if (MainPage.isNen) AudioManager.PauseResumeSounds(true);
                                            }
                                            else if (button.getName().Equals("PauseFrame_RePlay"))
                                            {
                                                if (MainPage.isNen) AudioManager.PauseResumeSounds(true);
                                                NewGame();
                                            }
                                            else if (button.getName().Equals("PauseFrame_Exit")) NavigationService.GoBack();
                                        }
                                    }
                                    #endregion
                                }
                                else if (isSelectSkill)// hoàn tất việc đặt skill
                                {
                                    #region đặt skill xuống
                                    if (!((indexSkill == 1 || indexSkill == 2) && Map.matrix[(int)getIndexTouch(curtouch).X, (int)getIndexTouch(curtouch).Y] != 0))
                                    {
                                        dat_thap.Play();
                                        mapEffects.Add(new MapEffect(indexSkill, getIndexTouch(curtouch)));
                                        Mana -= new MapEffect(indexSkill, getIndexTouch(curtouch)).getMana();
                                        TimeToUseEffectAgain[indexSkill] = new MapEffect(indexSkill, getIndexTouch(curtouch)).getTimeAgain();
                                        countTimeToUseEffectAgain[indexSkill] = 0;
                                        if (indexSkill == 0)
                                        {
                                            countAddLoc = 1;
                                            indexAddLoc = getIndexTouch(curtouch);
                                        }
                                        else if (indexSkill == 3)
                                        {
                                            mapEffects.Add(new MapEffect(indexSkill, getIndexTouch(curtouch), 1));
                                            mapEffects.Add(new MapEffect(indexSkill, getIndexTouch(curtouch), 2));
                                            mapEffects.Add(new MapEffect(indexSkill, getIndexTouch(curtouch), 3));
                                            mapEffects.Add(new MapEffect(indexSkill, getIndexTouch(curtouch), 4));
                                            mapEffects.Add(new MapEffect(indexSkill, getIndexTouch(curtouch), 5));
                                        }
                                    }
                                    #endregion
                                    #region reset lại các biến liên quan
                                    isSelectSkill = false;
                                    foreach (Button button in BookItems)
                                    {
                                        if (button.getName().Equals(indexSkill.ToString()))
                                        {
                                            button.setTouch(false);
                                        }
                                    }
                                    #endregion
                                }
                                else if (isSelectTower) // hoàn tất việc đặt tháp
                                {
                                    #region đặt tháp
                                    if (Map.matrix[(int)getIndexTouch(curtouch).X, (int)getIndexTouch(curtouch).Y] == 1)
                                    {
                                        dat_thap.Play();
                                        if (TypeTowerSelected == 0)
                                        {
                                            tower = new BasicTower(getIndexTouch(curtouch), 1, 0);
                                            tower.Load(contentManager);
                                            towers.Add(tower);
                                        }
                                        else if (TypeTowerSelected == 1)
                                        {
                                            tower = new BowTower(getIndexTouch(curtouch), 1, 0);
                                            tower.Load(contentManager);
                                            towers.Add(tower);
                                        }
                                        else if (TypeTowerSelected == 2)
                                        {
                                            tower = new CannonTower(getIndexTouch(curtouch), 1, 0);
                                            tower.Load(contentManager);
                                            towers.Add(tower);
                                        }
                                        else if (TypeTowerSelected == 3)
                                        {
                                            tower = new MagicTower(getIndexTouch(curtouch), 1, 0);
                                            tower.Load(contentManager);
                                            towers.Add(tower);
                                            countMagicTower--;
                                        }
                                        else
                                        {
                                            tower = new SoulTower(getIndexTouch(curtouch), 1, 0);
                                            tower.Load(contentManager);
                                            towers.Add(tower);
                                        }
                                        Money -= (int)tower.getPrice();
                                        Map.matrix[(int)getIndexTouch(curtouch).X, (int)getIndexTouch(curtouch).Y] = 2;
                                    }
                                    #endregion
                                    #region reset lại các biến liên quan
                                    isSelectTower = false;
                                    foreach (Button button in Gamebuttons)
                                    {
                                        if (button.getName().Equals(TypeTowerSelected.ToString()))
                                        {
                                            button.setTouch(false);
                                        }
                                    }
                                    #endregion
                                }
                                else if (upgradeTower.getVisible()) // hoàn tất việc nâng cấp
                                {
                                    #region
                                    upgradeTower.isTouch(curtouch, contentManager, true);
                                    #endregion
                                }
                                else if (curtouch.X > 170 && curtouch.Y >= 410)
                                {
                                    #region xử lí việc bấm nút mua tháp
                                    foreach (Button button in Gamebuttons)
                                    {
                                        if (!button.getName().Equals("") && button.isTouch(curtouch, Vector2.Zero))
                                        {
                                            if (button.getName().Equals("buyMana"))
                                            {
                                                button.setTouch(false);
                                                click.Play();
                                                if (Mana < 200 && banggia.CheckAvailable(MapAndUpgrade.UpgradeInterface.Gold, 200 - Mana).X != 0)
                                                {
                                                    MessageBoxResult result = MessageBox.Show("Bạn có muốn dùng ngọc để nạp đầy mana không ?", "Mua mana", MessageBoxButton.OKCancel);
                                                    if (result == MessageBoxResult.OK)
                                                    {
                                                        click.Play();
                                                        banggia.PriceMana(MapAndUpgrade.UpgradeInterface.Gold, 200 - Mana);
                                                    }
                                                    else
                                                    {
                                                        click.Play();
                                                    }
                                                }
                                                else
                                                {
                                                }
                                            }
                                            else if (!button.getName().Equals("book"))
                                            {
                                                click.Play();
                                                TypeTowerSelected = Convert.ToInt16(button.getName()); // lấy loại tháp
                                                #region kiểm tra xem đủ tiền mua tháp không
                                                if (TypeTowerSelected == 0 && Money >= new BasicTower(Vector2.Zero, 1, 0).getPrice())
                                                {
                                                    isSelectTower = true;
                                                }
                                                else if (TypeTowerSelected == 1 && Money >= new BowTower(Vector2.Zero, 1, 0).getPrice())
                                                {
                                                    isSelectTower = true;
                                                }
                                                else if (TypeTowerSelected == 2 && Money >= new CannonTower(Vector2.Zero, 1, 0).getPrice())
                                                {
                                                    isSelectTower = true;
                                                }
                                                else if (countMagicTower > 0 && TypeTowerSelected == 3 && Money >= new MagicTower(Vector2.Zero, 1, 0).getPrice())
                                                {
                                                    isSelectTower = true;
                                                }
                                                else if (TypeTowerSelected == 4 && Money >= new SoulTower(Vector2.Zero, 1, 0).getPrice())
                                                {
                                                    isSelectTower = true;
                                                }
                                                else
                                                {
                                                    button.setTouch(false);
                                                    isSelectTower = false;
                                                }
                                                #endregion
                                            }
                                            else
                                            {
                                                click.Play();
                                                button.setTouch(false);
                                                isBookOpenned = !isBookOpenned;
                                            }
                                        }
                                    }
                                    #endregion
                                }
                                else if (curtouch.X <= 170 && curtouch.Y >= 410)
                                {
                                    #region xử lí việc bấm pause và tăng speed
                                    foreach (Button button in Gamebuttons)
                                    {
                                        if (!button.getName().Equals("") && button.isTouch(curtouch, Vector2.Zero))
                                        {
                                            click.Play();
                                            button.setTouch(false);
                                            if (!GameStatus.Equals("Pause") && button.getName().Equals("pause"))
                                            {
                                                if (MainPage.isNen) AudioManager.PauseResumeSounds(false);
                                                GameStatus = "Pause";
                                            }
                                            else if (button.getName().Equals("speed1"))
                                            {
                                                if (Speed == 1) Speed = 2;
                                                else Speed = 1;
                                            }
                                        }
                                    }
                                    #endregion
                                }
                                else if (curtouch.X >= 720 && isBookOpenned)
                                {
                                    #region xử lí các nút chức năng
                                    for (int i = 0; i < 4; i++)
                                    {
                                        if (countTimeToUseEffectAgain[i] >= 100 && BookItems[i].isTouch(curtouch))
                                        {
                                            click.Play();
                                            BookItems[i].setTouch(false);
                                            if (Mana >= new MapEffect(i, Vector2.Zero).getMana())
                                            {
                                                isSelectSkill = true;
                                                indexSkill = i;
                                            }
                                        }
                                    }
                                    #endregion
                                }

                                else
                                {
                                    #region xử lí việc nâng cấp
                                    for (int i = 0; i < towers.Count; i++)
                                    {
                                        if (towers[i].getIndex() == getIndexTouch(curtouch))
                                        {
                                            click.Play();
                                            upgradeTower = new UpgradeTower(towers[i], i);
                                            upgradeTower.Load(contentManager);
                                        }
                                    }
                                    #endregion
                                }
                            }
                        }
                    }
                    #endregion
                }
                else
                {
                    #region xử lí tại giao diện thắng - thua
                    TouchCollection touchs = TouchPanel.GetState();
                    foreach (TouchLocation touch in touchs)
                    {
                        if (touch.State == TouchLocationState.Pressed)
                        {
                            start = touch.Position;
                            curtouch = touch.Position;
                        }
                        if (touch.State == TouchLocationState.Moved)
                        {
                            curtouch = touch.Position;
                            foreach (Button button in EndGameButtons)
                            {
                                if (!button.getName().Equals("") && !button.getName().Equals("Win") && !button.getName().Equals("Lose"))
                                {
                                    button.isTouch(curtouch);
                                }
                            }
                        }
                        if (touch.State == TouchLocationState.Released)
                        {
                            curtouch = touch.Position;
                            foreach (Button button in EndGameButtons)
                            {
                                if (!button.getName().Equals("") && !button.getName().Equals("Win") && !button.getName().Equals("Lose"))
                                {
                                    if (button.isTouch(curtouch))
                                    {
                                        click.Play();
                                        button.setTouch(false);
                                        if (GameStatus.Equals("Win") && button.getName().Equals("Win_Face"))
                                        {
                                            ShareLinkTask shareLinkTask = new ShareLinkTask();

                                            shareLinkTask.Title = "Tớ đã vượt qua level " + Level.ToString() + " với số điểm " + Score.ToString() + " , ai hơn tớ nào ?";
                                            shareLinkTask.LinkUri = new Uri("http://www.windowsphone.com/vi-VN/store/publishers?publisherId=qplay", UriKind.Absolute);
                                            shareLinkTask.Message = "Bạn có muốn phá kỉ lục của tớ không ?";

                                            shareLinkTask.Show();
                                        }
                                        else if (GameStatus.Equals("Win") && button.getName().Equals("Win_Next"))
                                        {
                                            NavigationService.GoBack();
                                        }
                                        else if (GameStatus.Equals("Lose") && button.getName().Equals("Lose_Menu"))
                                        {
                                            NavigationService.GoBack();
                                        }
                                        else if (GameStatus.Equals("Lose") && button.getName().Equals("Lose_RePlay"))
                                        {
                                            NewGame();
                                        }
                                    }
                                }
                            }
                        }
                    }
                    #endregion
                }
            }
        }

        private void OnDraw(object sender, GameTimerEventArgs e)
        {
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.Black);
            // TODO: Add your drawing code here 
            spriteBatch.Begin();
            spriteBatch.Draw(TopicImage, Dolech, new Microsoft.Xna.Framework.Rectangle(0, 0, 800, 480), Color.White, 0f, Vector2.Zero, new Vector2(Map.SizeOfMatrix.Y / 800, Map.SizeOfMatrix.X / 480) * 128 * Scale, SpriteEffects.None, 0f);

            map.Draw(spriteBatch);
            if (!GameStatus.Equals("Win") && !GameStatus.Equals("Lose"))
            {
                #region vẽ các ô trống để đặt tháp và skill
                if (isSelectTower || isSelectSkill) // vẽ các ô trống có thể đặt tháp
                {
                    for (int i = 0; i < (int)(Map.SizeOfMatrix.X * Map.SizeOfMatrix.Y); i++)
                    {
                        if (Map.matrix[i / (int)Map.SizeOfMatrix.Y, i % (int)Map.SizeOfMatrix.Y] == (isSelectTower ? 1 : 0))
                            spriteBatch.Draw(Otrong, (new Vector2(i % (int)Map.SizeOfMatrix.Y, i / (int)Map.SizeOfMatrix.Y) * 128) * Scale + Dolech, new Microsoft.Xna.Framework.Rectangle(0, 0, 128, 128), Color.White, 0f, Vector2.Zero, Scale, SpriteEffects.None, 0f);
                    }
                }
                #endregion
                #region vẽ các tháp và nâng cấp
                foreach (Tower tower in towers)
                {
                    tower.Draw(contentManager, spriteBatch);
                }
                if (upgradeTower.getVisible())
                {
                    upgradeTower.Draw(spriteBatch, priceFont, contentManager);
                }
                #endregion
                #region vẽ các hiệu ứng skill và quái vật
                foreach (MapEffect effect in mapEffects)
                {
                    if (effect.getType() == 1 || effect.getType() == 2)
                        effect.Draw(spriteBatch, contentManager);
                }
                for (int i = monsters.Count - 1; i >= 0; i--)
                {
                    if (!monsters[i].getIsEnable()) monsters.RemoveAt(i);// nếu không tồn tại nữa thì xóa đi
                    else monsters[i].Draw(spriteBatch, contentManager);
                }
                foreach (MapEffect effect in mapEffects)
                {
                    if (effect.getType() == 0 || effect.getType() == 3)
                        effect.Draw(spriteBatch, contentManager);
                }
                #endregion
            }
            if (!isSelectTower && !upgradeTower.getVisible() && !isSelectSkill)
            {
                #region khi đang chọn tướng or chọn thì không hiển thị các button
                foreach (Button button in Gamebuttons)
                {
                    if (GameStatus.Equals("Pause") && button.getName().Equals("pause")) { }
                    else if (Speed == 1 && button.getName().Equals("speed2")) { }
                    else if (Speed == 2 && button.getName().Equals("speed1")) { }
                    else if (!GameStatus.Equals("Pause") && button.getName().StartsWith("PauseFrame")) { }
                    else if (!(isBookOpenned && button.getName().Equals("book")))
                        button.Draw(spriteBatch, Vector2.Zero);
                    spriteBatch.DrawString(priceFont, new BasicTower(Vector2.Zero, 1, 0).getPrice().ToString(), new Vector2(310, 450), Color.White);
                    spriteBatch.DrawString(priceFont, new BowTower(Vector2.Zero, 1, 0).getPrice().ToString(), new Vector2(380, 450), Color.White);
                    spriteBatch.DrawString(priceFont, new CannonTower(Vector2.Zero, 1, 0).getPrice().ToString(), new Vector2(450, 450), Color.White);
                    spriteBatch.DrawString(priceFont, new MagicTower(Vector2.Zero, 1, 0).getPrice().ToString(), new Vector2(520, 450), Color.White);
                    spriteBatch.DrawString(priceFont, countMagicTower.ToString(), new Vector2(530, 400), Color.Red);
                    spriteBatch.DrawString(priceFont, new SoulTower(Vector2.Zero, 1, 0).getPrice().ToString(), new Vector2(590, 450), Color.White);
                }
                if (isBookOpenned) // khi mở sách
                {
                    for (int i = 0; i < 4; i++)
                    {
                        BookItems[i].TimeAgainDraw(spriteBatch, (int)countTimeToUseEffectAgain[i]);
                        spriteBatch.DrawString(priceFont, new MapEffect(i, Vector2.Zero).getMana().ToString(), new Vector2(768, 155 + 76 * i), Color.White);
                    }
                    BookItems[4].Draw(spriteBatch, Vector2.Zero);
                }
                spriteBatch.DrawString(font, Mana.ToString(), new Vector2(650, 425), (isBookOpenned ? Color.Blue : Color.White));
                #endregion
            }
            else
            {
                #region chỉ hiển thị các thanh công cụ bt
                foreach (Button button in Gamebuttons)
                {
                    if (button.getName().Equals(""))
                        button.Draw(spriteBatch, Vector2.Zero);
                }
                #endregion
            }
            #region nơi đặt các string lên màn hình
            //spriteBatch.DrawString(font, Level.ToString(), new Vector2(100, 100), Color.White);
            spriteBatch.DrawString(font, Score.ToString(), new Vector2(357, 1), Color.White);
            if (Money < 0) MessageBox.Show("Lỗi Tiền Âm");
            spriteBatch.DrawString(font, Money.ToString(), new Vector2(48, 6), Color.White);
            spriteBatch.DrawString(font, CurLife.ToString() + "/" + Life.ToString(), new Vector2(645, 4.5f), Color.White);
            spriteBatch.DrawString(waveFont, waveMonster.ToString() + " / 30", new Vector2(357, 36), Color.White);
            if (GameStatus.Equals("Pause"))
                spriteBatch.DrawString(font, "Tạm dừng", new Vector2(300, 120), Color.White);
            //spriteBatch.DrawString(font, (DeviceStatus.ApplicationCurrentMemoryUsage / 1024 / 1024).ToString(), new Vector2(300, 300), Color.Red);
            if (monsters.Count == 0 && countToCreateAMonster <= 300) spriteBatch.DrawString(waveFont, ((300 - countToCreateAMonster) / 30).ToString(), new Vector2(680, 60), Color.White);
            if (GameStatus.Equals("Win") || GameStatus.Equals("Lose"))
            {
                foreach (Button button in EndGameButtons)
                {
                    if (button.getName().Equals("")) { button.Draw(spriteBatch, Vector2.Zero); }
                    else if (GameStatus.Equals("Win") && !button.getName().StartsWith("Win")) { }
                    else if (GameStatus.Equals("Lose") && !button.getName().StartsWith("Lose")) { }
                    else
                    {
                        button.Draw(spriteBatch, Vector2.Zero);
                    }
                }
                spriteBatch.DrawString(font, "Tổng điểm : " + (Score + CurLife * 200 + Money), new Vector2(250, 220), Color.White);
                spriteBatch.DrawString(font, "Kỷ lục    : " + ((Score + CurLife * 200 + Money) > curHighScore ? (Score + CurLife * 200 + Money) : curHighScore), new Vector2(270, 260), Color.White);
                if (GameStatus.Equals("Win"))
                {
                    ImageStar = contentManager.Load<Texture2D>("images/winlose/sao" + Star);
                    spriteBatch.Draw(ImageStar, new Vector2(275, 20), new Rectangle(0, 0, 125, 61), Color.White, 0, Vector2.Zero, 2, SpriteEffects.None, 0);
                }
            }
            #endregion

            spriteBatch.End();
        }
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            click.Play();
            if (isSelectSkill) isSelectSkill = false;
            else if (isSelectTower) isSelectTower = false;
            else if (upgradeTower.getVisible()) upgradeTower.setVisible(false);
            else if (!GameStatus.Equals("Lose") && !GameStatus.Equals("Win"))
            {
                if (GameStatus.Equals("Pause"))
                {
                    GameStatus = "Play";
                    if (MainPage.isNen) AudioManager.PauseResumeSounds(true);
                }
                else
                {
                    if (MainPage.isNen) AudioManager.PauseResumeSounds(false);
                    GameStatus = "Pause";
                }
            }
            e.Cancel = true;
            if (GameStatus.Equals("Lose") || GameStatus.Equals("Win")) { e.Cancel = false; }
        }
        public static Vector2 getIndexTouch(Vector2 touch)
        {
            Vector2 temp = (touch - Dolech) / Scale;
            Vector2 vitri = new Vector2((int)(temp.Y / 128), (int)(temp.X / 128));
            if (vitri.X < 0) vitri.X = 0;
            if (vitri.Y < 0) vitri.Y = 0;
            if (vitri.X >= Map.SizeOfMatrix.X) vitri.X = Map.SizeOfMatrix.X - 1;
            if (vitri.Y >= Map.SizeOfMatrix.Y) vitri.Y = Map.SizeOfMatrix.Y - 1;
            return vitri;
        } //tính toán vị trí ng dùng đã lựa chọn trên màn hình
    }
}